/*
 * File Name：ActivityJumpManager.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ActivityJumpManager.java
 * Modify By：res-jxliu
 * Modify Date：2015年3月21日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.ui.BrowserActivity;
import com.ciwong.mobilelib.ui.BrowserActivity.IntentString;
import com.ciwong.mobilelib.ui.CameraActivity;
import com.ciwong.mobilelib.ui.CropImgActivity;
import com.ciwong.mobilelib.ui.InstallActivity;
import com.ciwong.mobilelib.ui.ScanImageActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.util.ArrayList;

/**
 * 界面跳转管理类
 *
 * @author res-jxliu
 * @version ciwong v.1.0 2015年3月21日
 * @since ciwong v.1.0
 */
public class BaseJumpManager {
    /**
     * 返回键文字资源ID
     */
    public static final String GO_BACK_ID = "GO_BACK_ID";

    /**
     * activity启动来源
     */
    public static final String INTENT_FLAG_SOURCE = "INTENT_FLAG_SOURCE";

    /**
     * 图片URL地址集合
     */
    public static final String IMAGE_URLS = "IMAGE_URLS";

    /**
     * 图片选中索引
     */
    public static final String CURRENT_INDEX = "CURRENT_INDEX";

    /**
     * 是否需要显示右边按钮
     */

    public static final String IS_SHOWRIGHT = "IS_SHOWRIGHT";

    /**
     * 获取baseIntent
     *
     * @param goBackId 返回按钮的文字id
     * @param act      启动activity
     * @param cls      将要打开的activity
     * @return intent
     */
    public static Intent getBaseIntent(int goBackId, Activity act, Class cls) {
        Intent intent = new Intent(act, cls);
        intent.putExtra(INTENT_FLAG_SOURCE, true);
        intent.putExtra(GO_BACK_ID, goBackId);
        return intent;
    }

    /**
     * 跳转到应用程序安装
     *
     * @param context     上下文
     * @param apkFilePath 应用包路径
     */
    public static void jumpToInstall(Context context, String apkFilePath) {
        Intent intent = new Intent(context, InstallActivity.class);
        intent.putExtra(INTENT_FLAG_SOURCE, true);
        intent.putExtra(CWUpdate.UpdateVersion.APK_FILE_PATH, apkFilePath);
        context.startActivity(intent);
    }

    /**
     * 跳转到照相机
     *
     * @param act         发起页面
     * @param goBackId    返回键的stringId
     * @param requestCode 请求码
     */
    public static void jumpToCamera(Activity act, int goBackId, int requestCode) {
        Intent intent = getBaseIntent(goBackId, act, CameraActivity.class);
        act.startActivityForResult(intent, requestCode);
    }

    /**
     * 调转到浏览器
     *
     * @param act
     * @param goBackId
     * @param url      网址
     * @param titile   标题
     */
    public static void jumpToBrowser(Activity act, int goBackId, String url,
                                     String titile) {
        Intent intent = getBaseIntent(goBackId, act, BrowserActivity.class);
        intent.putExtra(IntentString.INTENT_STRING_URL, url);
        intent.putExtra(IntentString.INTENT_STRING_TITLE, titile);
        act.startActivity(intent);
    }


    /**
     * 跳转到系统浏览器
     *
     * @param context 上下文
     * @param uri     URI
     */
    public static void jumpToSysBrowser(Activity context, Uri uri) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.putExtra(BaseJumpManager.INTENT_FLAG_SOURCE, true);
            context.startActivity(intent);
        } catch (Exception e) {
            CWToast.makeText(context, "请安装浏览器", CWToast.LENGTH_SHORT, true)
                    .show();
        }
    }

    /**
     * 跳转到系统选择文件
     *
     * @param act
     * @param jumpCode 跳转码
     */
    public static void jumpToSysChooseVideoPic(Activity act, int jumpCode) {
        try {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            Intent chooserIntent = Intent.createChooser(i, "File Chooser");
            chooserIntent.putExtra(INTENT_FLAG_SOURCE, true);
            act.startActivityForResult(chooserIntent, jumpCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到系统选择文件
     *
     * @param act
     * @param jumpCode 跳转码
     */
    public static void jumpToSysChooseVideoFile(Activity act, int jumpCode) {
        try {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("video/*");
            Intent chooserIntent = Intent.createChooser(i, "File Chooser");
            chooserIntent.putExtra(INTENT_FLAG_SOURCE, true);
            act.startActivityForResult(chooserIntent, jumpCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void jumpToChoosePic(Activity activity, int count,
                                       int jumpCode) {
        Matisse.from(activity)
                .choose(MimeType.ofImage())//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(count)//可选的最大数
                .capture(true)//选择照片时，是否显示拍照
                .captureStrategy(new CaptureStrategy(true, "${applicationId}.login.contentprovider.sqlite"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(jumpCode);
    }


    /**
     * 跳转至头像剪切Ativity
     *
     * @param act
     * @param goBackId
     * @param imagePath   文件绝对路径
     * @param requestCode
     */
    public static void jumpToCropImage(Activity act, int goBackId,
                                       String imagePath, int requestCode) {
        Intent intent = getBaseIntent(goBackId, act, CropImgActivity.class);
        intent.putExtra(CropImgActivity.INTENT_IMAGE_PATH, imagePath);
        intent.putExtra(BaseIntentFlag.INTENT_FLAG_TYPE, requestCode);
        act.startActivityForResult(intent, requestCode);
    }

    /**
     * 跳转到系统裁剪照片
     *
     * @param activity
     * @param uri
     * @param requestCode
     * @param isNeedOut   是否需要输出
     */
    public static void jumpToSysCropPhoto(Activity activity, Uri uri, Uri outPutPaht, File mOnputFile,
                                          int requestCode, boolean isNeedOut, int outputX, int outputY) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.putExtra(INTENT_FLAG_SOURCE, true);
        intent.setDataAndType(uri, "image/*");
//        Log.e("jumpToSysCropPhoto", "uri=====" + uri);
//        Log.e("jumpToSysCropPhoto", "outPutPaht=====" + outPutPaht);
        if (isNeedOut) {
            //纠结了一上午Mark一下：
            //outputUri一定是使用Uri.fromFile(file)生成的，而不是使用FileProvider.getUriForFile
//            if (Build.VERSION.SDK_INT >= 30) {
//            intent.setDataAndType(outPutPaht, "image/*");
            //android 11以上，将文件创建在公有目录
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mOnputFile.getAbsolutePath()));
//            } else {
//                intent.setDataAndType(uri, "image/*");
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutPaht);
//            }
        }
        intent.putExtra("crop", "true");
        int os = OSUtils.getRomType();

        switch (os) {
            case OSUtils.RomType.OS_TYPE_EMUI:
                intent.putExtra("aspectX", 9998);
                intent.putExtra("aspectY", 9999);
                break;
            default:
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                break;
        }
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
//        intent.putExtra("return-data", uri != null);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        if (Build.VERSION.SDK_INT >= 30) {
            //向intent传入 MediaStore.EXTRA_OUTPUT参数后，表明这是一个存储动作
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutPaht);
            intent.putExtra("return-data", false); //是否将数据保留在Bitmap中返回
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出格式，一般设为Bitmap格式及图片类型
            intent.putExtra("noFaceDetection", true); //是否去除面部检测
        } else {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mOnputFile.getAbsolutePath()));
        }
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 从URI中获取真实路径
     *
     * @param context
     * @param contentUri
     * @return
     */
    public static String getRealPathFromURI(Context context, Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj,
                null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
            }
            cursor.close();
        }
        return res;
    }

    /**
     * 跳转到查看图片界面(一般用于显示头像)
     *
     * @param act
     * @param goBackId
     * @param imgPath
     */
    public static void jumpToScanImage(Activity act, int goBackId,
                                       String imgPath) {
        ArrayList<String> imgPashs = new ArrayList<String>();
        imgPashs.add(imgPath);
        Intent intent = getBaseIntent(goBackId, act, ScanImageActivity.class);
        intent.putStringArrayListExtra(IMAGE_URLS, imgPashs);
        intent.putExtra(BaseIntentFlag.INTENT_FLAG_TYPE,
                BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_NO);
        act.startActivity(intent);
    }

    /**
     * 跳转到查看图片界面
     *
     * @param goBackId
     * @param act
     * @param urls
     * @param index
     */
    public static void jumpToScanImage(Activity act, int goBackId,
                                       ArrayList<String> urls, int index) {
        Intent intent = getBaseIntent(goBackId, act, ScanImageActivity.class);
        intent.putStringArrayListExtra(IMAGE_URLS, urls);
        intent.putExtra(CURRENT_INDEX, index);
        act.startActivity(intent);
    }

    /**
     * 跳转到浏览图片页面
     *
     * @param act         Activity对象类
     * @param goBackId    返回ID
     * @param urlList     图片地址数组
     * @param index       第几个
     * @param action
     * @param type
     * @param requestCode 请求码
     */
    public static void jumpToScanImage(Activity act, int goBackId,
                                       ArrayList<String> urlList, int index, int action, int type,
                                       int requestCode) {
        Intent mIntent = getBaseIntent(goBackId, act, ScanImageActivity.class);
        mIntent.putExtra(IMAGE_URLS, urlList);
        mIntent.putExtra(BaseIntentFlag.INTENT_FLAG_ACTION, action);
        mIntent.putExtra(BaseIntentFlag.INTENT_FLAG_TYPE, type);
        mIntent.putExtra(CURRENT_INDEX, index);
        act.startActivityForResult(mIntent, requestCode);
    }

    /**
     * 调用系统相机
     *
     * @param activity
     * @param tempFile
     * @param jumpCode
     */
    public static void jumpToSysCamera(Activity activity, File tempFile,
                                       int jumpCode) {
        Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraintent.putExtra(INTENT_FLAG_SOURCE, true);
        // 指定调用相机拍照后照片的储存路径
        Uri fileUri = FileProvider7.getUriForFile(activity, tempFile);
        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        activity.startActivityForResult(cameraintent, jumpCode);
    }

    /**
     * 跳转到录像
     */
    public static void jumpToVideo(Activity act, File tempFile, int jumpCode) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        Uri fileUri = FileProvider7.getUriForFile(act, tempFile);
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        //设置视频录制的最长时间
        //intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //设置视频录制的画质
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        act.startActivityForResult(intent, jumpCode);
    }

    /**
     * 调用系统相机
     *
     * @param fragment
     * @param tempFile
     * @param jumpCode
     */
    public static void jumpToSysCamera(Fragment fragment, File tempFile,
                                       int jumpCode) {
        Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraintent.putExtra(INTENT_FLAG_SOURCE, true);
        // 指定调用相机拍照后照片的储存路径
        Uri fileUri = FileProvider7.getUriForFile(fragment.getContext(), tempFile);
        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        fragment.startActivityForResult(cameraintent, jumpCode);
    }

    /**
     * 跳转到系统选择文件
     *
     * @param act
     * @param jumpCode 跳转码
     */
    public static void jumpToSysChooseFile(Activity act, int jumpCode,
                                           boolean isImg) {
        try {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(isImg ? "image/*" : "*/*");
            Intent chooserIntent = Intent.createChooser(i, "File Chooser");
            chooserIntent.putExtra(INTENT_FLAG_SOURCE, true);
            act.startActivityForResult(chooserIntent, jumpCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到系统相册
     *
     * @param act      相册
     * @param jumpCode 跳转码
     */
    public static void jumpToSysAlbum(Activity act, int jumpCode) {
        try {
            Intent getAlbum = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            getAlbum.putExtra(INTENT_FLAG_SOURCE, true);
            // getAlbum.setType("image/*");
            act.startActivityForResult(getAlbum, jumpCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到系统相册
     *
     * @param act      相册
     * @param jumpCode 跳转码
     */
    public static void jumpToSysAlbum(Fragment act, int jumpCode) {
        try {
            Intent getAlbum = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            getAlbum.putExtra(INTENT_FLAG_SOURCE, true);
            // getAlbum.setType("image/*");
            act.startActivityForResult(getAlbum, jumpCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到图片浏览， 附带跳转码 显示标题栏与底部栏
     *
     * @param act         activity
     * @param goBackId    返回id
     * @param requestCode 请求码
     * @param jumpCode    跳转码
     */
    public static void jumpToScanImageWithJumpCode(Activity act, int goBackId,
                                                   int jumpCode, int requestCode) {
        Intent albumIntent = getBaseIntent(goBackId, act,
                ScanImageActivity.class);
        albumIntent.putExtra(ScanImageActivity.INTENT_FLAG_JUMP_CODE, jumpCode);
        albumIntent.putExtra(BaseIntentFlag.INTENT_FLAG_TYPE,
                BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_ALL);
        act.startActivityForResult(albumIntent, requestCode);
    }


}
